package cn.edu.zsc.rbac.service.array;

import cn.edu.zsc.rbac.domain.dto.RoleDto;
import cn.edu.zsc.rbac.domain.entity.Role;
import cn.edu.zsc.rbac.domain.vo.RoleVo;
import cn.edu.zsc.rbac.domain.vo.Result;
import cn.edu.zsc.rbac.service.IDeptService;
import cn.edu.zsc.rbac.service.IRoleService;
import cn.edu.zsc.rbac.service.IUserService;

import java.time.LocalDateTime;


/**
 * 业务层-角色
 *
 * @author 陈奕君
 * @since 2025/4/15 18:29
 */
public class RoleService extends BaseService<Role,RoleDto,RoleVo> implements IRoleService{

    private IUserService userService;

    public static IRoleService singleton;

    public RoleService() {
        data = new Role[DATA_SIZE + 1];
        temp = new RoleVo[DATA_SIZE + 1];
    }

    public static IRoleService getInstance() {
        if (singleton == null) {
            singleton = new RoleService();
        }
        return singleton;
    }

    @Override
    RoleVo convertToVo(Role role) {
        return new RoleVo(role.getId(), role.createAt, role.updateAt, role.name, role.dataScope);
    }

    @Override
    Role createEntity(RoleDto dto,int id)
    {
        LocalDateTime now = LocalDateTime.now();
        return new Role(id,now,now,dto.name,dto.dataScope);
    }

    @Override
    void updateEntity(RoleDto dto,Role role)
    {
        role.updateAt = LocalDateTime.now();
        role.name = dto.name;
        role.dataScope = dto.dataScope;
    }

    @Override
    public  Result delete(int id) {
        if (!existsById(id)) {
            return Result.failure("删除角色失败，角色不存在！");
        }
        if(userService == null){
            userService = UserService.getInstance();
        }
        if(userService.roleInUse(id))
        {
            return Result.failure("删除失败，还有用户属于该角色，不能删除！");
        }
        data[id] = null;
        return Result.success("删除角色成功！", id);
    }
}